package ywpt.web.action.config;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletException;

import ywpt.components.acegi.domain.Operation;
import ywpt.core.Constants;
import ywpt.core.SystemMessage;
import ywpt.core.exception.UniqueConstraintException;
import ywpt.core.util.DateTools;
import ywpt.core.util.StringTools;
import ywpt.core.web.BaseAction;
import ywpt.model.CommonTable;
import ywpt.model.CommonTypes;
import ywpt.service.config.CommonTableService;
import ywpt.service.config.CommonTypesService;
import ywpt.web.common.OperationConstants;
import ywpt.web.common.PublicFunction;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.interceptor.validation.SkipValidation;
import org.ecside.table.limit.Limit;
import org.ecside.util.RequestUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;

public class CommonTableAction extends BaseAction implements Preparable,ModelDriven<CommonTable>{

	/**
	 * ������Ϣ��Action
	 */
	private static final long serialVersionUID = -8198262744328482285L;
	protected final Log			log	= LogFactory.getLog(CommonTableAction.class);
	private Long				id;
	private Long				townId;  //��������
	private Long 				areaId;
	private String				commonTypesId; //����������Ϣ����
	private String				commonTypesCode;//����������Ϣ���Code
	private List<CommonTable>	commonTableList	= new ArrayList<CommonTable>();
	private CommonTable			commonTable;
	private String				fieldId;
	private String				fieldCode;
	private String				fieldType;
	private String				searchString;
	private CommonTableService  commonTableService;
	protected static int		DEFAULT_PAGE_SIZE	= 20;
	protected static String		ENC_ALGORITHM		= "MD5";
	private boolean[] popedom=new boolean[Constants.POPEDOM_LEN];
	private int version;
	private CommonTypesService  commonTypesService;
	
	@Override
	public void prepare() throws Exception {
		if(getId()!=null)
			this.commonTable=commonTableService.getEntityById(getId());
		else
			this.commonTable=new CommonTable();
		HashMap<String,Operation> oper=this.getOperMapByUser(this.getCurrentUser());
		PublicFunction.getOperationPopedom(oper,popedom,OperationConstants.CONFIG_commonTable);		
	}

	@Override
	public CommonTable getModel() {
		return commonTable;
	}

	protected void showInformation()
	{
		if(commonTable.getCommonTypes()!=null)
		{
			CommonTypes commonTypes=commonTable.getCommonTypes();
			this.setCommonTypesId(String.valueOf(commonTypes.getId()));
		}
		
	}
	
	protected void getData(DetachedCriteria query)
	{   

		query.add(Restrictions.eq("deleteFlag", false));
		int totalRows=RequestUtils.getTotalRowsFromRequest(getRequest());
		if(totalRows<0)
		{
			totalRows=commonTableService.getEntityCountByCriteria(query);
		}
		int[] rowStartEnd=RequestUtils.getRowStartEnd(getRequest(),totalRows,
				DEFAULT_PAGE_SIZE,0);
		Limit limit=RequestUtils.getLimit(getRequest(),"ec",totalRows,
				DEFAULT_PAGE_SIZE);
		int pageSize=limit.getCurrentRowsDisplayed();	
		query.addOrder(Order.asc("code"));
		query.setProjection(null);
		commonTableList.addAll(commonTableService.getEntitys(query,
				pageSize,rowStartEnd[0]));
	}

	
	public String execute()
	{
		return null;
	}

	public String list()
	{
		commonTableList.clear();
		DetachedCriteria query=DetachedCriteria.forClass(CommonTable.class);		
		if (!StringTools.isNullOrSpace(searchString))
		{	try 
			{
				return this.search();
			} 
			catch (Exception e) 
			{
				this.addActionMessage(SystemMessage.SEARCH_ERROR);
				return SUCCESS;
			}
		}
		this.getData(query);
		return SUCCESS;
	}

	public String search() throws Exception
	{
		commonTableList.clear();
		DetachedCriteria query=DetachedCriteria.forClass(CommonTable.class);
		if(!StringTools.isNullOrSpace(fieldCode)&&!StringTools.isNullOrSpace(fieldCode))
		{
			try
			{
				if(fieldCode.indexOf(".")!=-1)
				{
					String object=fieldCode.substring(0,fieldCode.indexOf("."));
					String property=fieldCode.substring(fieldCode.indexOf(".")+1);
					query.createAlias(object,object);
					if(this.fieldType.equals("date"))
					{
						query.add(Restrictions
								.eq(object+"."+property,DateTools.strToDate(
										this.getSearchString(),"yyyy-MM-dd")));
					}
					else if(this.fieldType.equals("digital"))
					{
						query.add(Restrictions.eq(object+"."+property,this
								.getSearchString()));
					}
					else if(this.fieldType.equals("int"))
					{
						query.add(Restrictions.eq(object+"."+property,Integer
								.parseInt(this.getSearchString())));
					}
					else if(this.fieldType.equals("boolean"))
					{
						query.add(Restrictions.eq(object+"."+property,Boolean
								.valueOf(this.getSearchString())));
					}
					else
					{
						query.add(Restrictions.like(object+"."+property,"%"
								+this.getSearchString()+"%"));
					}
				}
				else
				{
					if(this.fieldType.equals("date"))
					{
						query.add(Restrictions
								.eq(fieldCode,DateTools.strToDate(this
										.getSearchString(),"yyyy-MM-dd")));
					}
					else if(this.fieldType.equals("digital"))
					{
						query.add(Restrictions.eq(fieldCode,this
								.getSearchString()));
					}
					else if(this.fieldType.equals("int"))
					{
						query.add(Restrictions.eq(fieldCode,Integer
								.parseInt(this.getSearchString())));
					}
					else if(this.fieldType.equals("boolean"))
					{
						query.add(Restrictions.eq(fieldCode,Boolean
								.valueOf(this.getSearchString())));
					}
					else
					{
						query.add(Restrictions.like(fieldCode,"%"
								+this.getSearchString()+"%"));
					}
				}
			}
			catch(Exception e)
			{
				this.addActionMessage(SystemMessage.CONDITION_FORMAT_ERROR);
				return SUCCESS;
			}
		}
		this.getData(query);
		return SUCCESS;
	}
	
	public String query()
	{
		commonTableList.clear();
		DetachedCriteria query=DetachedCriteria.forClass(CommonTable.class);		
		this.getData(query);
		return SUCCESS;
	}
	
	
	
	
	@SkipValidation
	public String input()
	{    
		return INPUT;
	}
	
	@SuppressWarnings("unchecked")
	public String edit()
	{
		commonTable=commonTableService.getEntityById(id);
		showInformation();
		return INPUT;
	}
	
	@SuppressWarnings("unchecked")
	public String save() throws ServletException
	{  
		CommonTypes commonTypes=new CommonTypes();		
		if(!StringTools.isNullOrSpace(this.getCommonTypesId())){
			commonTypes=commonTypesService.getEntityById((Long.parseLong(this.getCommonTypesId())));
		}
		commonTable.setCommonTypes(commonTypes);
		commonTable.setUpdateDate(new Date());
		commonTable.setUpdater(this.getCurrentUser().getFullName());
		try
		{
			if(id==null)
			{
				commonTableService.save(commonTable);
				this.addActionMessage(SystemMessage.SAVE_SUCCESS);
			}
			else
			{
				if(!commonTable.isCheckFlag())
				{
					if(this.getVersion()==commonTable.getVersion())
					{
						commonTableService.update(commonTable);
						this.addActionMessage(SystemMessage.UPDATE_SUCCESS);
					}
					else
						this.addActionMessage(SystemMessage.UPDATE_FAIL);
				}
				else
					this.addActionMessage(SystemMessage.AUDITING_SAVE);
			}			
		}	
		catch (UniqueConstraintException e) 
		{
			this.addActionError(SystemMessage.SAVE_FAIL+e.getMessage());
			return SUCCESS;
		}
		showInformation();
		return SUCCESS;
	}

	public String check()
	{
		if(id==null){
			this.addActionMessage(SystemMessage.NO_OBJECT);
			
		}else{
			commonTable=commonTableService.getEntityById(id);
		if(!commonTable.isCheckFlag())
		{
			commonTable.setChecker(this.getCurrentUser().getFullName());
			commonTable.setCheckDate(DateTools.getDateTypeDate());
			commonTable.setCheckFlag(true);
			commonTableService.update(commonTable);
			this.addActionMessage(SystemMessage.AUDITING_SUCCESS);
		}
		else
			this.addActionMessage(SystemMessage.AUDITING_REPEAT);
		
		}
		showInformation();
		return SUCCESS;
	}
	
	public String discheck()
	{
		if(id==null){
			this.addActionMessage(SystemMessage.NO_OBJECT);
			
		}else{
			commonTable=commonTableService.getEntityById(id);
		if(commonTable.isCheckFlag())
		{
			commonTable.setChecker(null);
			commonTable.setCheckDate(null);
			commonTable.setCheckFlag(false);
			commonTableService.update(commonTable);
			this.addActionMessage(SystemMessage.DISAUDITING_SUCCESS);
		}
		else
			this.addActionMessage(SystemMessage.DISAUDITING_REPEAT);
		
		}
		showInformation();
		return SUCCESS;
	}
	
	public String delete()
	{
		if(id!=null)
		{
			if(!commonTable.isCheckFlag())
				commonTableService.remove(id);
			else
			{
				this.addActionMessage(SystemMessage.DELETE_AUDITING_FAIL);
				showInformation();
				return INPUT;
			}
		}
		else
		{
			this.addActionMessage(SystemMessage.NO_OBJECT);
			showInformation();
			return INPUT;
		}			
		return SUCCESS;
	}
	
	
	public String select()
	{
		DetachedCriteria query=DetachedCriteria.forClass(CommonTable.class);
		/*
		if(townId!=null)
			query.createAlias("town","town").add(Restrictions.eq("town.id",townId));*/
		
		if(!StringTools.isNullOrSpace(commonTypesCode))
			query.createAlias("commonTypes","commonTypes").add(Restrictions.eq("commonTypes.code",commonTypesCode));
		
		query.add(Restrictions.eq("deleteFlag",false));
		commonTableList.addAll(commonTableService.getEntitys(query));			
		return SUCCESS;
	}

	
	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getCommonTypesId() {
		return commonTypesId;
	}

	public void setCommonTypesId(String commonTypesId) {
		this.commonTypesId = commonTypesId;
	}

	public Long getTownId() {
		return townId;
	}

	public void setTownId(Long townId) {
		this.townId = townId;
	}

	public Long getAreaId() {
		return areaId;
	}

	public void setAreaId(Long areaId) {
		this.areaId = areaId;
	}

	public List<CommonTable> getCommonTableList() {
		return commonTableList;
	}

	public void setCommonTableList(List<CommonTable> commonTableList) {
		this.commonTableList = commonTableList;
	}

	public CommonTable getCommonTable() {
		return commonTable;
	}

	public void setCommonTable(CommonTable commonTable) {
		this.commonTable = commonTable;
	}

	public String getFieldId() {
		return fieldId;
	}

	public void setFieldId(String fieldId) {
		this.fieldId = fieldId;
	}

	public String getFieldCode() {
		return fieldCode;
	}

	public void setFieldCode(String fieldCode) {
		this.fieldCode = fieldCode;
	}

	public String getFieldType() {
		return fieldType;
	}

	public void setFieldType(String fieldType) {
		this.fieldType = fieldType;
	}

	public String getSearchString() {
		return searchString;
	}

	public void setSearchString(String searchString) {
		this.searchString = searchString;
	}

	public CommonTableService getCommonTableService() {
		return commonTableService;
	}

	public void setCommonTableService(CommonTableService commonTableService) {
		this.commonTableService = commonTableService;
	}

	public boolean[] getPopedom() {
		return popedom;
	}

	public void setPopedom(boolean[] popedom) {
		this.popedom = popedom;
	}

	public int getVersion() {
		return version;
	}

	public void setVersion(int version) {
		this.version = version;
	}

	public static long getSerialVersionUID() {
		return serialVersionUID;
	}

	public Log getLog() {
		return log;
	}

	public CommonTypesService getCommonTypesService() {
		return commonTypesService;
	}

	public void setCommonTypesService(CommonTypesService commonTypesService) {
		this.commonTypesService = commonTypesService;
	}

	public String getCommonTypesCode()
	{
		return commonTypesCode;
	}

	public void setCommonTypesCode(String commonTypesCode)
	{
		this.commonTypesCode=commonTypesCode;
	}
    
	
}
